package com.graduation.mathematics.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.graduation.mathematics.R;
import com.graduation.mathematics.bean.Ranking;

import java.util.List;

public class RankingAdapter extends RecyclerView.Adapter<RankingAdapter.RankingViewHolder> {

    private List<Ranking> mData;
    private Context mContext;
    private LayoutInflater mLayoutInflater;
    protected OnItemClickListener mOnItemClickListener;

    public RankingAdapter(List<Ranking> data, Context context) {
        mData = data;
        mLayoutInflater = LayoutInflater.from(context);
        mContext = context;
    }

    @NonNull
    @Override
    public RankingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new RankingViewHolder(mLayoutInflater.inflate(R.layout.layout_item_ranking, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RankingViewHolder holder, int position) {
        Ranking ranking = mData.get(position);
        if (ranking == null) {
            return;
        }
        Glide.with(mContext).load(ranking.getImgUrl()).into(holder.imgRanking);
        holder.tvNum.setText(String.valueOf(position +1));
        holder.tvDate.setText(ranking.getDate());
        holder.tvDes.setText(ranking.getDes());
        holder.itemView.setOnClickListener(v -> mOnItemClickListener.onItemClick(holder.imgRanking, ranking.getImgUrl()));
    }

    @Override
    public int getItemCount() {
        return  mData.isEmpty() ? 0 : mData.size();
    }

    public void updateData(List<Ranking> list){
        if (list != null && list.size() > 0){
            mData = list;
            notifyDataSetChanged();
        }
    }

    class RankingViewHolder extends RecyclerView.ViewHolder {
        TextView tvNum;
        ImageView imgRanking;
        TextView tvDate;
        TextView tvDes;

        RankingViewHolder(@NonNull View itemView) {
            super(itemView);
            tvNum = itemView.findViewById(R.id.tv_num);
            imgRanking = itemView.findViewById(R.id.ranking_img);
            tvDate = itemView.findViewById(R.id.ranking_item_date);
            tvDes = itemView.findViewById(R.id.ranking_item_des);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(ImageView imageView, String imageUrl);
    }

    public void setOnItemClickListener(OnItemClickListener mOnItemClickListener) {
        this.mOnItemClickListener = mOnItemClickListener;
    }
}
